<template>
  <view
    id="azm-custom-component"
    class="cu-custom"
    :class="{ hide: hideNavBar === true }"
  >
    <view
      class="azm-global-fixed-lr"
      :class="mode == 'custom-nav' ? 'bottom-line' : ''"
      id="navBarCustom"
    >
      <view
        :style="CustomBarStyle"
        class="flex flex-direction"
        v-if="!isHideNavigation"
      >
        <view
          class="status-bar"
          :style="StatusBarStyle"
          @click="handleStatusBarClick"
        />
        <view class="nav-bar flex-sub" :style="NavBarContentStyle">
          <block v-if="mode === 'search-custom'">
            <search-custom
              :isBack="navigationBar.isBack"
              :placeholder="navigationBar.placeholder"
              :disabled="navigationBar.disabled"
              @search_tap="handleSearchClick"
              @search_input="_emit"
              @search_confirm="_emit"
              @search_blur="_emit"
            />
          </block>
          <block v-else-if="mode == 'custom-nav'">
            <scroll-view scroll-x class="bg-white nav custom-nav">
              <view
                class="cu-item cu-color"
                :class="index == TabCur ? 'text-black ac_cur' : ''"
                v-for="(item, index) in customNav"
                :key="index"
                @click="tabSelect"
                :data-id="index"
              >
                {{ item }}
              </view>
            </scroll-view>
          </block>
          <block v-else>
            <cu-custom
              :isBack="navigationBar.isBack"
              :title="navigationBar.title"
              :backText="navigationBar.backText"
              :backType="navigationBar.backType"
              @cuBack="handleBack"
              @cuToHome="handleToHome"
            />
          </block>
        </view>
      </view>
      <slot />
    </view>
    <view v-if="!fullscreen" :style="NavBarStyle" class="cu-custom-bg" />
  </view>
</template>

<script>
import { mapState } from "vuex";
import cuCustom from "./cu-custom.vue";
import searchCustom from "./search-custom.vue";
import { debounce } from "@u/lodash/throttle";

export default {
  name: "nar-bar",
  components: {
    cuCustom,
    searchCustom,
  },
  data() {
    const systemInfo = this.SystemInfo || {};
    const object2style = this.$util.object2style;
    return {
      TabCurs: 0,
      Custom: {},
      StatusBar: systemInfo.StatusBar,
      CustomBar: systemInfo.CustomBar,
      StatusBarStyle: object2style({
        height: systemInfo.StatusBar + "px",
      }),
      CustomBarStyle: object2style({
        height: systemInfo.CustomBar + "px",
      }),
      NavBarStyle: object2style({
        height: systemInfo.CustomBar + "px",
      }),
      NavBarContentStyle: "",
      HideNavigation: false,
    };
  },
  computed: {
    ...mapState({
      systemInfo: (state) => state.System.systemInfo,
    }),
    navBarStyle() {
      const object2style = this.$util.object2style;
      const { StatusBar, CustomBar, Custom, windowWidth } = this.systemInfo;
      this.setStyle();
    },
    isHideNavigation() {
      let HideNavigation = this.HideNavigation;
      let hideNavigation = this.hideNavigation;
      let hideStatusBar = this.hideStatusBar;
      switch (true) {
        case HideNavigation === true && hideNavigation === false:
          return false;
        case hideNavigation === true || HideNavigation === true:
          return true;
        default:
          return false;
      }
    },
    navigationBar() {
      const { jude, mapKeys } = this.$util;
      let obj = {};
      let options = !jude.isEmptyObject(this.options, true) ? this.options : {};
      if (jude.isEmpty(options.backgroundColor)) {
        options.backgroundColor = "#FFFFFF";
        options.isBackgroundEmpty = true;
      }
      mapKeys(options, obj, true);
      if (!jude.isNumberOfNaN(obj.backType)) obj.backType = 0;
      return obj;
    },
  },
  watch: {
    ["systemInfo.CustomBar"]() {
      this.setStyle();
    },
    ["fullscreen"]() {
      this.setStyle();
    },
  },
  created() {},
  mounted() {
    // 设置容器的高度
    this.setStyle();
  },
  props: {
    TabCur: {
      type: Number,
      default: 0,
    },
    customNav: {
      type: Array,
      default: [],
    },
    options: {
      type: Object,
      default(data) {
        return data;
      },
    },
    methods: {
      type: Object,
      default(data) {
        return data;
      },
    },
    mode: {
      type: String,
      default: "cu-custom",
    },
    to: String,
    hideNavBar: Boolean,
    fullscreen: Boolean,
    isOnBack: Boolean,
    // 插槽高度 rpx
    slotHeight: {
      type: Number,
      default: 0,
    },
  },
  methods: {
    // 后退
    async handleBack(e) {
      const cur = this.$util.getCurrentPage(1);
      const result = await this.handleEventBackOut();
      if (result !== false) {
        if (cur && cur.route) {
          this.$$router.back();
        } else {
          this.toHome();
        }
      }
    },
    async handleToHome() {
      const result = await this.handleEventBackOut();
      result !== false && this.toHome();
    },
    toHome() {
      this.$$router.replaceAll("/pages/home/index");
    },
    handleBackOut() {
      let that = this;
      return new Promise((resolve) => {
        that.$emit("onBackOut", function(data) {
          resolve(data);
        });
      });
    },
    async handleEventBackOut() {
      let handleBackOut = true;
      if (this.methods && this.methods.handleBackOut) {
        handleBackOut = this.methods.handleBackOut();
      } else if (this.isOnBack === true) {
        handleBackOut = await this.handleBackOut();
      }

      if (handleBackOut && handleBackOut.constructor === Promise) {
        return handleBackOut;
      } else {
        return Promise.resolve(handleBackOut);
      }
    },
    setStyle: debounce(function() {
      let vm = this;
      const { object2style, $$$setTimeout } = vm.$util;
      const { StatusBar, CustomBar, Custom, windowWidth } = vm.systemInfo;
      const { backgroundColor, color, isBackgroundEmpty } = this.navigationBar;
      vm.Custom = Custom;
      let CustomBarStyle = {};
      if (StatusBar > 0) {
        vm.StatusBar = StatusBar;
        vm.StatusBarStyle = object2style({
          height: StatusBar + "px",
        });
      }
      if (CustomBar > 0) {
        vm.CustomBar = CustomBar;
        if (vm.mode == "custom-nav") {
          CustomBarStyle.height = CustomBar + 15 + "px";
        } else {
          CustomBarStyle.height = CustomBar + "px";
        }
      }
      let fullscreen = this.fullscreen;
      if (backgroundColor && !fullscreen)
        CustomBarStyle.backgroundColor = backgroundColor;
      else if (fullscreen && isBackgroundEmpty === true)
        CustomBarStyle.backgroundColor = "rgba(255,255,255,.2)";
      else CustomBarStyle.backgroundColor = backgroundColor;
      if (color) CustomBarStyle.color = color;
      vm.CustomBarStyle = object2style(CustomBarStyle);
      // #ifdef MP-WEIXIN
      const l = windowWidth - Custom.right;
      vm.NavBarContentStyle = object2style({
        width: `${Custom.left}px`,
      });
      // #endif
      vm.getNavBarCustom();
      // $$$setTimeout(vm.getNavBarCustom, 500);
    }, 300),
    getNavBarCustom() {
      const that = this;
      const { object2style } = this.$util;
      const SelectorQuery = uni.createSelectorQuery();
      SelectorQuery.in(this);
      const NodesRef = SelectorQuery.select(
        "#navBarCustom"
      ).boundingClientRect();
      that.$nextTick(function() {
        NodesRef.exec(function([d]) {
          if(!d)return;
          that.NavBarStyle = object2style({
            height: d.height + "px",
          });
          that._emit(d, "load");
        });
      });
    },
    handleSearchClick(e) {
      const { jude, mapKeys } = this.$util;
      this._emit(e, "tap");
      if (!jude.isEmpty(this.to)) this.$$router.push(this.to);
    },
    _emit(e, t) {
      const type = e.type === "click" ? "tap" : e.type;
      this.$emit(`navBar${this.firstToUpperCase(t || type)}`, e.detail || e);
    },
    firstToUpperCase(s) {
      return typeof s === "string"
        ? s.slice(0, 1).toUpperCase() + s.slice(1)
        : "";
    },
    handleStatusBarClick(e) {
      this._emit(e, "onStatusBarClick");
    },
    tabSelect(e) {
      this._emit(e, "tabSelect");
      this.$emit("tabSelect", e);
    },
  },
};
</script>

<style lang="scss" scoped>
$nar-bar-height: 44px;
$status-bar-height: 20px;

.hide {
  display: none;
}

.azm-global-fixed-lr {
  z-index: 800;

  > .flex {
    height: calc(#{$nar-bar-height} + #{$status-bar-height});
  }
}

.status-bar {
  width: 100%;
  height: var(--status-bar-height);
}

.nav-bar {
  width: 100%;
}

.cu-custom-bg {
  height: calc(#{$nar-bar-height} + #{$status-bar-height});
  background-color: #ffffff;
}

.custom-nav {
  font-size: 30upx;
  font-weight: bold;
  padding-left: 14 * 2upx;
  .cu-item {
    margin: 0;
    padding: 0;
    &:first-child {
      margin-right: 43upx;
    }
  }

  .cu-color {
    color: #a2a8a8;
  }

  .text-black {
    font-size: 38upx;
    color: #313131;
  }
}

.bottom-line {
  // margin: 0 28upx;
  z-index: 0;
}
</style>
